import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

class DatePickerPage extends StatefulWidget {
  @override
  _DatePickerPageState createState() => _DatePickerPageState();
}

class _DatePickerPageState extends State<DatePickerPage> {
  final now = new DateTime.now();
  final nowSt = new DateTime.now().millisecondsSinceEpoch;

  String datePickerText;
  String timePickerText;

  void _showDatePicker() {
    // 方法1用then回调
    showDatePicker( // showDatePicker是个Future类型的方法，相当于js的Promise，可以接then回调
        context: context,
        initialDate: this.now,
        firstDate: new DateTime(1970),
        lastDate: new DateTime(2020)
    ).then((result){
      print(result);
    });
  }

  // 方法2用async await回调
  void _showDatePicker2() async {
    // 方法1用then回调
    var result = await showDatePicker( // showDatePicker是个Future类型的方法，相当于js的Promise，可以接then回调
        context: context,
        initialDate: this.now,
        firstDate: new DateTime(1970),
        lastDate: new DateTime(2021)
    );
    setState(() {
      this.datePickerText = formatDate(result, [yyyy, '年', mm, '月', dd, '日']);
    });
  }

  TimeOfDay _nowTime = TimeOfDay(hour: 0, minute: 0);
  void _showTimePicker() {
    showTimePicker(context: context, initialTime: this._nowTime).then((time){
      setState(() {
        this._nowTime = time;
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('日期组件'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text('当前日期：$now'),
          Text('当前日期时间戳：$nowSt'),
          Text('时间戳转日期：${DateTime.fromMicrosecondsSinceEpoch(nowSt*1000)}'),
          Text('date_format格式化插件：${formatDate(DateTime.now(), [yyyy, '年', mm, '月', dd, '日'])}'),
          SizedBox(height: 30,),
          InkWell( // 可以点击的组件
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(datePickerText??'选择日期'),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: this._showDatePicker2,
          ),
          SizedBox(height: 30,),
          InkWell( // 可以点击的组件
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('${this._nowTime!=null?this._nowTime.format(context):'选择时间'}'),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: this._showTimePicker,
          )
        ],
      ),
    );
  }
}
